import pywraps2 as s2
import redis
import math

p1 = s2.S2LatLng.FromDegrees(23.12255, 113.29973).ToPoint()
radius = 200.0  #200 meters of radius
degree = radius/(40076020/2)*180
angle = s2.S1Angle.Degrees(degree)
geofence = s2.S2Cap(p1, angle)
geofence_cell_level = 12
geofence_cell_level_bits = geofence_cell_level * 2 + 3

# lat - Circle center latitude, float
# lon - Circle center longitude, float
# degree - radius distance reprensent by degree, float
def createCircleGeoFence(lat, lon, degree):
    center = s2.S2LatLng_FromDegrees(lat, lon).ToPoint()
    angle = s2.S1Angle.Degrees(degree)
    geofence = s2.S2Cap(center, angle)
    return geofence

# geofence - S2Cap
# level - S2 Cell level
# Return cell ids, list of S2 Cells id
def getGeoFenceCellId(geofence, level):
    rc = s2.S2RegionCoverer()
    rc.set_fixed_level(level)
    cells = rc.GetCovering(geofence)
    cells_id = []
    for cell in cells:
        cells_id.append(cell.id())
    return cells_id

# Get the S2 cell contains child cell id range
def getChildCellIdRange(cellid):
    remaining_bits = 64-geofence_cell_level_bits
    cell_level_bits = int(math.pow(2, geofence_cell_level_bits+1)-1)<<remaining_bits
    cell_begin = cellid & cell_level_bits
    cell_end = cell_begin + int(math.pow(2, remaining_bits))
    return cell_begin, cell_end

# geofenceId - S2Region instance dict key
# lat, lon - location 
def checkGeofenceContain(geofenceId, lat, lon):
    if geofenceId in geofence_dict:
        point = s2.S2LatLng.FromDegrees(lat, lon).ToPoint()
        return geofence_dict['geofenceId'].contains(point)
    else:
        geofence_meta = redis.get(geofenceId)
        if geofence_meta:
            if geofence_meta['type'] == 'circle':
                geofence = 'a'
        else:   # geofence not exist in redis, need to delete the record in cellid-geofence relation
            #redis.del()
            geofence = 'b'

def enterGeofence(geofenceId, vin):
    print('Vin %s enters Geofence %s' %(geofenceId, vin))

def exitGeofence(geofenceId, vin):
    print('Vin %s exits Geofence %s' %(geofenceId, vin))

